; Input interrupt handler (int 31h)
int31h_handler:

	push	i31h_end

	; AH = function number
	cmp	ah,	0h
	je	i31_0			; function 0
	dec	ah
	jz	i31_1			; function 1 - get keystroke

	ret

	i31_0:
		mov	eax,	0h	; operation successfull
		ret		; done

; AH=1: gets keystroke
;	Returns:	AX - keystroke data
;	Works by reading data from keyboard buffer
;	Deletes data after reading

	i31_1:
		sti			; allow interrupts
		push	ebx		; save registers
		push	es
		
		mov	ax,	40h	; Setting ES to BIOS data segment
		mov	es,	ax
	.loop:	
		mov bx, [es:0x1A]	; Pointer to head of keyboard buffer
		mov ax, [es:0x1C]	; Pointer to tail of keyboard buffer
	
		cmp	ax,	bx	;check if buffer is empty
		je	.loop
		
		cli			; disable interrupts
		mov	ax,	[es:bx]	; read keystroke data
		cmp	bx,	0x3C	; check if head points to last avaible address
		je	.@@1
		add	bx,	2
		jmp	.@@2
		.@@1:
		mov	bx,	0x1E	; and set it to first address if so
		.@@2:
		mov	[es:0x1A],	bx
		sti
		
		pop	es
		pop	ebx		; restore registers
		ret		; done

; interrupt ends here
	i31h_end:
iret
